package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.cmpe.group6.storyroad.ListAdapters.MostRecentAdapter;
import com.cmpe.group6.storyroad.jsonClasses.MostRecentStoryHolder;
import com.cmpe.group6.storyroad.jsonClasses.ServerResponseObject;
import com.cmpe.group6.storyroad.jsonClasses.StoryView;
import com.google.gson.Gson;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link MostRecentFragment.OnFragmentInteractionListener} interface to handle
 * interaction events. Use the {@link MostRecentFragment#newInstance} factory
 * method to create an instance of this fragment.
 * 
 */
public class MostRecentFragment extends Fragment {

	private StoryView[] mostRecentStories;
	private MostRecentTask mTask;
	private ListView list;
	private int updateInterval = 20000;
	private Handler updateHandler;

	private ProgressBar progressBar;

	private static MostRecentAdapter adapter;
	private final static ArrayList<String> story_titles = new ArrayList<String>();
	private final static ArrayList<String> story_ratings = new ArrayList<String>();
	private final static ArrayList<String> story_tags = new ArrayList<String>();
	private final static ArrayList<String> story_ids = new ArrayList<String>();

	public MostRecentFragment() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment

		View holder = inflater.inflate(R.layout.tab1, container, false);

		list = (ListView) holder.findViewById(R.id.listView1);
		progressBar = (ProgressBar) holder
				.findViewById(R.id.progressBar_recent);

		mTask = new MostRecentTask();
		mTask.execute((Void) null);

		return holder;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		updateHandler = new Handler();

		// Clicking a list item will direct user to that story's page.
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				String storyId = (String) list.getItemAtPosition(position);
				Intent readStoryIntent = new Intent(getActivity(),
						ReadStoryActivity.class);
				readStoryIntent.putExtra("story_id", storyId);
				startActivity(readStoryIntent);
			}
		});

		startRepeatingTask();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	// Thread for regularly updating the list.
	void startRepeatingTask() {
		final Handler handler = new Handler();
		Timer timer = new Timer();
		TimerTask doAsynchronousTask = new TimerTask() {
			@Override
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						try {
							mTask = new MostRecentTask();
							// PerformBackgroundTask this class is the class
							// that extends AsynchTask
							mTask.execute((Void) null);
						} catch (Exception e) {
							// TODO Auto-generated catch block
						}
					}
				});
			}
		};
		timer.schedule(doAsynchronousTask, 0, updateInterval);
	}

	/**
	 * Represents an asynchronous Most Recent task for getting most recent
	 * stories from the server.
	 * 
	 */
	public class MostRecentTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			progressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME
					+ "MostRecentStories");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						3);
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				mostRecentStories = gson.fromJson(jsonResponse,
						MostRecentStoryHolder.class).mostRecentStories;

				story_titles.clear();
				story_ratings.clear();
				story_tags.clear();
				story_tags.clear();
				story_ids.clear();
				for (int i = 0; i < mostRecentStories.length; i++) {
					StoryView storyView = mostRecentStories[i];
					story_titles.add(storyView.getTitle());
					story_ratings.add(String.valueOf(storyView.getAvgRating()));
					story_tags.add(storyView.getTags());
					story_ids.add(String.valueOf(storyView.getS_id()));
				}

				adapter = new MostRecentAdapter(getActivity(), story_titles,
						story_ratings, story_tags, story_ids);

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(getActivity(), "Connection Error",
						Toast.LENGTH_SHORT).show();
			}
			list.setAdapter(adapter);
			progressBar.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {

		}
	}

}
